#include"gua.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<errno.h>
/**
 * gotgua为输入的卦象，以12位的0、1序列表示
 * 11,10,01,00分别代表太阳，少阳，少阴，太阴
 **/
int init_gua(gua_t *gua,const char *gotgua){
	int creatbyhuman = 0;//是否人工起卦，默认为随机起卦

	char validgotgua[13];
	strncpy(validgotgua,gotgua,13);

	if(strlen(validgotgua)==12){
		creatbyhuman = 1;
		char *ptr = validgotgua;
		while(*ptr != '\0'){
			if(*ptr!='1' && *ptr !='0'){
				creatbyhuman=0;
				break;
			}
			ptr++;
		}
	}

	if(!creatbyhuman){
		//random
		validgotgua[0]='\0';
		int i=0;
		srand(time(NULL));
		for(;i<6;i++){
			int yao = rand()%4;
			switch(yao){
				case 0:	strcat(validgotgua,"00");	break;
				case 1:	strcat(validgotgua,"01");	break;
				case 2:	strcat(validgotgua,"10");	break;
				case 3:	strcat(validgotgua,"11");	break;
			}
		}
	}

	int i=0;
	for(;i<6;i++){
		//本卦
		gua->bengua[i]=validgotgua[2*i];
		//有爻变的位置置为1,表示对应位为太阴或太阳
		if(validgotgua[i]==validgotgua[i+1]){
			gua->yaoflag[i] = '1';
		}else{
			gua->yaoflag[i] = '0';
		}
		//之卦
		if(gua->yaoflag[i]=='0'){
			gua->zhigua[i]=gua->bengua[i];
		}else{
			if(gua->bengua[i]=='1'){
				gua->zhigua[i]='0';
			}else{
				gua->zhigua[i]='1';
			}
		}
	}
	//互卦
	gua->hugua[0]=gua->bengua[1];
	gua->hugua[1]=gua->bengua[2];
	gua->hugua[2]=gua->bengua[3];
	gua->hugua[3]=gua->bengua[2];
	gua->hugua[4]=gua->bengua[3];
	gua->hugua[5]=gua->bengua[4];

	if(creatbyhuman){
		puts("手动起卦成功");
	}else{
		puts("随机起卦成功");
	}

	return 0;
}



int readguaci(const char *guaxiang){
	char *path = (char*)malloc(50);
	strcpy(path,"../data/");
	strcat(path,guaxiang);
	errno = 0;
	FILE *file = fopen(path,"r");
	free(path);
	if(errno){
		perror("读取卦辞出错");
		exit(1);
	}else{
		char *guaci = (char *)malloc(1024);
		while(fgets(guaci,1024,file)!=NULL){
			fputs(guaci,stdout);
		}
		free(guaci);
	}
	fclose(file);
	return 0;
}

